timeContribuyentePredio = function(rowid) {
	params = $.extend(rowid, {
    	mhresum: $("#mhresum").val(),
    	vnrodoc: $("#vnrodoc").val()
    });
	
    _post = $.post(path + "registro/listarpredio", params);
    _post.success(function(request){
        $("#panelRegistro").html(request);
    });
};

verContribuyentePredio = function(rowid) {
    if(typeof rowid == 'object') {
        parameters = rowid[0];
    } else {
        parameters = $(this).getRowData(rowid);
    }
    
    if($("#mhresum").val() == undefined || $("#mhresum").val() == null) {
    	panelPersona(parameters, function() {
    		timeContribuyentePredio(parameters);
    	});
    } else {
    	timeContribuyentePredio(parameters);
    }
};

verDetalle = function(rowid) {
	row = $("#tblResult").jqGrid('getRowData', rowid);
	ajaxDialog = false;
	panelPersona(row);
};

gridCompleteTblResult = function(){
	var ids = $("#tblResult").jqGrid('getDataIDs');
	for(var i=0; i < ids.length; i++){ 
		id = ids[i]; 
		bt = "<a style='height:20px;width:20px;' class='btnGrid' href='javascript: void(0);' onclick=\"verDetalle('"+id+"');\"><img src='" + pathImage + "find.png'/></a>";
		$("#tblResult").jqGrid('setRowData', ids[i], {modedit: bt});
	}
};

optionContribuyente = {
    width: 1000,
    colNames: ["C\u00F3digo", "Administrado", "Direcci\u00F3n Fiscal"],
    colModel: [
        {name:'cidpers', index:'cidpers', width:80, align: 'center'},
        {name:'crazsoc', index:'crazsoc', width:420},
        {name:'direccf', index:'direccf', width:420} ],
    caption: "&nbsp;&nbsp;&nbsp;Resultados de la busqueda",
    onSelectRow: verDetalle,
    ondblClickRow: verContribuyentePredio
};
bindkeysContribuyente = {"onEnter": verContribuyentePredio};

verViaPredio = function(rowid){
    row = $("#tblResult").jqGrid('getRowData', rowid);
    parameters = {
        "mperson": row.cidpers,
        "vnombre": row.crazsoc,
        "vdirecf": row.direccf,
        "mpredio": row.idsigma,
        "mhresum": row.mhresum,
        "cperiod": row.cperiod
    };
    _post = $.post(path + "registro/verpredio", parameters);
    _post.success(function(request){
        $("#panelRegistro").html(request);
    });
};

optionViaPredio = {
    height: "auto",
    width: 1000,
    colNames: [
        'idsigma', 'C\u00F3d. Predio', 'Direcci\u00F3n', 'mviadis', 'dnumero',
        'dmanzan', 'dnlotes', 'ddepart', 'dinteri', 'drefere',
        'dletras', 'destaci', 'ddeposi', 'ccatast', 'cplanos',
        'ctipmer', 'dnummer', 'cdiscat', 'czoncat', 'cmzacat',
        'cseccat', 'cltecat', 'cundcat', 'dbloque', 'dseccio',
        'dunidad', 'mpoblad', 'nestado', 'ctippre', 'idanexo',
        'ccodcuc', 'vhostnm', 'vusernm', 'ddatetm', 'nlatitu',
        'nlongit', 'nzoom'  , 'tnomvia', 'C\u00F3digo', 'Propietario',
        'direccf', 'vtipdoc', 'vnrodoc', 'vtippro', 'mhresum',
        'vnrodoc', 'cperiod'
    ],
    colModel: [
        {name: 'idsigma', index: 'idsigma', width: 1, hidden: true},
        {name: 'ccodpre', index: 'ccodpre', width: 70, align: 'center'},
        {name: 'vdirpre', index: 'vdirpre', width: 440},
        {name: 'mviadis', index: 'mviadis', width: 1, hidden: true},
        {name: 'dnumero', index: 'dnumero', width: 1, hidden: true},
        {name: 'dmanzan', index: 'dmanzan', width: 1, hidden: true},
        {name: 'dnlotes', index: 'dnlotes', width: 1, hidden: true},
        {name: 'ddepart', index: 'ddepart', width: 1, hidden: true},
        {name: 'dinteri', index: 'dinteri', width: 1, hidden: true},
        {name: 'drefere', index: 'drefere', width: 1, hidden: true},
        {name: 'dletras', index: 'dletras', width: 1, hidden: true},
        {name: 'destaci', index: 'destaci', width: 1, hidden: true},
        {name: 'ddeposi', index: 'ddeposi', width: 1, hidden: true},
        {name: 'ccatast', index: 'ccatast', width: 1, hidden: true},
        {name: 'cplanos', index: 'cplanos', width: 1, hidden: true},
        {name: 'ctipmer', index: 'ctipmer', width: 1, hidden: true},
        {name: 'dnummer', index: 'dnummer', width: 1, hidden: true},
        {name: 'cdiscat', index: 'cdiscat', width: 1, hidden: true},
        {name: 'czoncat', index: 'czoncat', width: 1, hidden: true},
        {name: 'cmzacat', index: 'cmzacat', width: 1, hidden: true},
        {name: 'cseccat', index: 'cseccat', width: 1, hidden: true},
        {name: 'cltecat', index: 'cltecat', width: 1, hidden: true},
        {name: 'cundcat', index: 'cundcat', width: 1, hidden: true},
        {name: 'dbloque', index: 'dbloque', width: 1, hidden: true},
        {name: 'dseccio', index: 'dseccio', width: 1, hidden: true},
        {name: 'dunidad', index: 'dunidad', width: 1, hidden: true},
        {name: 'mpoblad', index: 'mpoblad', width: 1, hidden: true},
        {name: 'nestado', index: 'nestado', width: 1, hidden: true},
        {name: 'ctippre', index: 'ctippre', width: 1, hidden: true},
        {name: 'idanexo', index: 'idanexo', width: 1, hidden: true},
        {name: 'ccodcuc', index: 'ccodcuc', width: 1, hidden: true},
        {name: 'vhostnm', index: 'vhostnm', width: 1, hidden: true},
        {name: 'vusernm', index: 'vusernm', width: 1, hidden: true},
        {name: 'ddatetm', index: 'ddatetm', width: 1, hidden: true},
        {name: 'nlatitu', index: 'nlatitu', width: 1, hidden: true},
        {name: 'nlongit', index: 'nlongit', width: 1, hidden: true},
        {name: 'nzoom'  , index: 'nzoom'  , width: 1, hidden: true},
        {name: 'tnomvia', index: 'tnomvia', width: 1, hidden: true},
        {name: 'cidpers', index: 'cidpers', width: 80, align: 'center'},
        {name: 'crazsoc', index: 'crazsoc', width: 390},
        {name: 'direccf', index: 'direccf', width: 1, hidden: true},
        {name: 'vtipdoc', index: 'vtipdoc', width: 1, hidden: true},
        {name: 'vnrodoc', index: 'vnrodoc', width: 1, hidden: true},
        {name: 'vtippro', index: 'vtippro', width: 1, hidden: true},
        {name: 'mhresum', index: 'mhresum', width: 1, hidden: true},
        {name: 'vnrodoc', index: 'vnrodoc', width: 1, hidden: true},
        {name: 'cperiod', index: 'cperiod', width: 1, hidden: true}
    ],
    caption: "&nbsp;&nbsp;&nbsp;Predios Registrados",
    onSelectRow: verDetalle,
    ondblClickRow: verViaPredio
};
bindkeysViaPredio = {"onEnter": verViaPredio};

buscarPredio = function() {
    parameters = {
        name: "tblResult",
        procedure: "pl_function.buscar_predio",
        print: "true",
        parameters: '{' +
        '"p_ccodpre":"' + $("#c_predial").val().toUpperCase() + '",' +
        '"p_ccodvia":"' + ccodvia.toUpperCase() + '",' +
        '"p_cnrovia":"' + $("#c_nroviacontrib").val().toUpperCase() + '",' +
        '"p_cmanzan":"' + $("#c_mzacontrib").val().toUpperCase() + '",' +
        '"p_cnrlote":"' + $("#c_lotecontrib").val().toUpperCase() + '"' +
        '}'
    };

    proceso = function(requestData){
        $("#panelResult").html('<table id="tblResult"></table><div id="ptblResult"></div><input type="hidden" id="ctblResult" name="ctblResult" value="" />');
        records = requestData.length;
    	_options = $.extend(optionViaPredio, {
			data: requestData,
	        datatype: "local"
    	});
        if(records == 0) {
            inicializarGrid("tblResult", _options);
            buttons = {
                "Aceptar": function(){
                    closeDialog("jqDialogInfo");
                    $('#c_codigocontrib').focus();
                }
            };
            openDialogInfo("No existen predios con los criterios de busqueda ingresados.", 380, 150, buttons);
        } else if(records >= 1) {
        	// TODO: Revisar cuando sea un predio
            inicializarGrid("tblResult", _options, bindkeysViaPredio);
        }
    };

    procesarConsultaSubProceso('registrar', parameters, proceso, 'json');
};

buscarContribuyente = function() {    
    parameters = {
        "name": "tblResult",
        "procedure": "public.buscar_persona",
        "print": "true",
        "parameters": '{' +
        '"p_nvar1":"' + $("#c_codigocontrib").val().toUpperCase() + '",' +
        '"p_nvar2":"' + $("#c_nombrecontrib").val().toUpperCase() + '",' +
        '"p_nvar3":"' + $("#c_apepatcontrib").val().toUpperCase() + '",' +
        '"p_nvar4":"' + $("#c_apematcontrib").val().toUpperCase() + '",' +
        '"p_nvar5":""' +
        '}'
    };

    proceso = function(requestData){
    	$("#panelResult").html('<table id="tblResult"></table><div id="ptblResult"></div><input type="hidden" id="ctblResult" name="ctblResult" value="" />');
    	records = requestData.length;
    	options = $.extend(optionContribuyente, {
			data: requestData,
	        datatype: "local"
    	});
        if(records == 0) {
            inicializarGrid("tblResult", options);
            buttons = {
                "Aceptar": function(){
                    closeDialog("jqDialogInfo");
                    $('#c_codigocontrib').focus();
                }
            };
            openDialogInfo("No existen contribuyentes con los criterios de busqueda ingresados.", 380, 150, buttons);
        } else if(records > 1) {
        	inicializarGrid("tblResult", options, bindkeysContribuyente);
        } else {
            verContribuyentePredio(requestData);
        }
    };

    procesarConsultaSubProceso('registrar', parameters, proceso, 'json');
};

$(function(){
    $("#c_codigocontrib").numeric({
        decimal: false, 
        negative: false
    }, function() {
        openDialogWarning("Solo Numeros Enteros Positivos.", 150, 90);
        this.value = "";
        this.focus();
    });
    
    $("#btnbuscar").button("option", "icons", {
        primary:'ui-icon-search'
    });
   
    inicializarGrid("tblResult", optionContribuyente);
    
    $("#panelContribuyente").on("keyup", "input", function(e) {
        if(e.keyCode == 13){
            $("#btnbuscar").click();
        }
    });
    
    $("#panelPredio").on("keyup", "input", function(e) {
    	var name = $(this).attr("id");
        if(e.keyCode == 13 && name != 'c_viacontrib'){
            $("#btnbuscar").click();
        }
    });
    
    $("#c_codigocontrib, #c_predial").on("focus", function() {
        $("#panelContribuyente input.ui-text").val("");
        $("#panelPredio input.ui-text").val("");
    });
    
    $(".pnl").on("focus", function() {
        var name = $(this).attr("id");
        if(name == 'c_viacontrib' || name == 'c_nroviacontrib' || name == 'c_mzacontrib' || name == 'c_lotecontrib') {
            $("#panelContribuyente input.ui-text").val("");
            $("#c_predial").val("");
        } else {
            $("#panelPredio input.ui-text").val("");
            $("#c_codigocontrib").val("");
        }
    });
    
    $("#btnbuscar").click(function(){
        valid = [false, false];
    
        if(trim($('#c_codigocontrib').val()).length > 0){
            $('#c_codigocontrib').val(LPad($('#c_codigocontrib').val(), 10, '0'));
        }

        valid[0] = valid[0] || (trim($("#c_nombrecontrib").val()).length > 0);
        valid[0] = valid[0] || (trim($("#c_apepatcontrib").val()).length > 0);
        valid[0] = valid[0] || (trim($("#c_apematcontrib").val()).length > 0);
        valid[0] = valid[0] || (trim($("#c_codigocontrib").val()).length > 0);

        if(trim($('#c_predial').val()).length > 0){
            $('#c_predial').val(LPad($('#c_predial').val(), 10, '0'));
        }

        valid[1] = valid[1] || (trim($("#c_predial").val()).length > 0);
        valid[1] = valid[1] || (trim($("#c_viacontrib").val()).length > 0);
        valid[1] = valid[1] || (trim($("#c_nroviacontrib").val()).length > 0);
        valid[1] = valid[1] || (trim($("#c_mzacontrib").val()).length > 0);
        valid[1] = valid[1] || (trim($("#c_lotecontrib").val()).length > 0);
    
        if(valid[0]) {
            buscarContribuyente();
        } else if(valid[1]) {
            buscarPredio();
        } else {
            openDialogWarning("Ingrese un valor en los campos de busqueda.", 380, 150);
        }
    });
    $("#c_codigocontrib").focus();
    
    $("#pnlPersona").dialog({
        title: "Nueva persona",
        modal: true,
        minHeight: 'auto',
        width: 820,
        position: ['center', 'center'],
        resizable: false,
        autoOpen: false,
        closeOnEscape: true
    });
});